import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from datetime import datetime, timedelta
import os

day = datetime.now()
Qdate = day.strftime('%Y-%m-%d %H:%M:%S')
yesterday = day - timedelta(days=1)
Ydate = yesterday.strftime('%Y-%m-%d')

# 获取指定文件绝对路径
def file_name(file_dir):
    alps_file=[]   
    for root, dirs, files in os.walk(file_dir):  
        for file in files:  
            if os.path.splitext(file)[1] == '.std':  
                alps_file.append(os.path.join(root, file))
    alps_file.sort()
    print('最新文件：', alps_file[-1])
    return alps_file[-1]

# 获取文件名
def filename(file_dir):
    alps_file=[]   
    for root, dirs, files in os.walk(file_dir):  
        for file in files:  
            if os.path.splitext(file)[1] == '.std':  
                alps_file.append(os.path.join(file))
    alps_file.sort()
    print('文件名：', alps_file[-1])
    return alps_file[-1]

file_dir = 'D:\\test\\test'
# SMTP服务器
mail_host="smtp.qq.com" 
# 邮箱用户名
mail_user="****@qq.com"
# 邮箱密码
mail_pass="****"
# 发件邮箱
sender = '****@qq.com'
# 收件邮箱
receivers = ['****@qq.com']

# 邮件信息
message = MIMEMultipart()
message['From'] = Header("***", 'utf-8')
message['To'] =  Header("***", 'utf-8')
message['Subject'] = Header(Ydate + '数据', 'utf-8')
message.attach(MIMEText('当前邮件发送时间{}'.format(Qdate), 'plain', 'utf-8'))

# 构造附件
att1 = MIMEText(open(file_name(file_dir), 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1.add_header('Content-Disposition', 'attachment', filename=filename(file_dir))
message.attach(att1)

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")
